#-*- coding:utf-8 -*-
from pymongo import MongoClient

#获取嵌套文档数组的值并进行修改
#
#{ "_id" : { "$oid" : "57c3d9836db807e0875fda55" }, "name" : "zs", "book" : [ { "math" : 1 }, { "math" : 1 }, { "math" : 1 } ] }
#{ "_id" : { "$oid" : "57c3d98f6db807e0875fda56" }, "name" : "ls", "book" : [ { "math" : 2 }, { "math" : 2  }, { "math" : 2 } ] }
#{ "_id" : { "$oid" : "57c3d99a6db807e0875fda57" }, "name" : "ww", "book" : [ { "math" : 3 }, { "math" : 3 }, { "math" : 3 } ] }

#
#


def MonClient():
  conn = MongoClient('127.0.0.1',27017)
  dbuse = conn.ok

  col = dbuse.ok

  coll = col.find()

  for item in coll:
    #将查询出来的列表转换成元组，及列表转换成元组 tuple()
    ob = tuple(item["book"])

    #列表长度
    lengh = len(item["book"])
    print "length" ,lengh
    
    #获取元组中的值,获取要更新的名字
    upname = item["name"]
    print item["name"]
    
    
    for up in range(lengh):
      om = ob[up]
      #获取元组中的值是字典，访问字典中的值
      upmath = om["math"]
      print upmath ,"====="
      upit = upmath + 5
      upbookid = "book.%d.math" % up
      
      dbuse.ok.update_one({"name":upname,"book.math":upmath},{"$set":{upbookid:upit}})

#
MonClient()

